// pages/resume/resume.js

import { Resume} from '../../models/resume'
import {check} from "../../util/identityCheck";
import {Publish} from "../../models/other"
import {RedPacket} from '../../models/redpacket'

let packetModel = new RedPacket()
const publishModel = new Publish()
const resumeModel = new Resume()

import UploadImg from '../../util/uploadImg'
const uploadImg = new UploadImg()

import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog'
function getShareId () {
  const shareId = wx.getStorageSync('otherId')
  if (shareId && shareId != 'undefined') { // 注意 这里是字符串类型的undefined 好奇我为什么没封装一下？因为我真的很忙
    return shareId
  } else {
    return ''
  }
}
Page({
  data: {
    countDown: 60,
    showMsg: false,
    totalMoney: 0,
    hasResume: false,
    showRedPacketDialog: false,
    Resume: {
      shareUserId: '',
      avatar: '',
      sex: '',
      title: '',
      birthday: '',
      phone: '',
      advantage: '',
      jobState: '',
      jobExperience: '',
      chooseStation: '',
      expectedCity: '',
      selfIntroduction: '',
      photoLife: '',
      photoLifeList: [],
      photoWork: '',
      photoWorkList: [],
      verificationCode: ''
    },
    showPopup: {
      sex: false,
      birthday: false,
      advantage: false,
      jobState: false,
      jobExperience: false,
      chooseStation: false,
      expectedCity: false
    },
    currentDate: new Date('1990/01/01').getTime(),
    minDate: new Date('1949/10/01').getTime(),
    maxDate: new Date().getTime(),
    advantageList: [],
    jobExperienceList: [],
    jobStationList: [],
    salaryList: [],
    cityList: ['河南', '广东', '江苏', '河北', '浙江', '上海', '山东', '福建', '江西', '陕西', '湖南', '四川', '湖北', '贵州', '安徽', '北京', '山西', '广西', '甘肃', '辽宁', '吉林', '重庆', '天津', '黑龙江', '云南', '内蒙古', '海南', '宁夏', '西藏', '青海', '新疆', '香港', '澳门', '台湾']
  },

  onShow (){
    const shareUserId = getShareId()
    setTimeout(() => {
      this.setData({
        'Resume.shareUserId': shareUserId
      })
    }, 1000)
    if(!check())return
  },

  chooseImage () {
    uploadImg.chooseImg(5,res => {
      let imgList = this.data.Resume.photoLifeList
      imgList.push(res)
      this.setData({
        'Resume.photoLifeList': imgList,
        'Resume.photoLife': imgList.join(',')
      })
    })
  },

  chooseWorkImage () {
    uploadImg.chooseImg(5,res => {
      let imgList = this.data.Resume.photoWorkList
      imgList.push(res)
      this.setData({
        'Resume.photoWorkList': imgList,
        'Resume.photoWork': imgList.join(',')
      })
    })
  },

  async publish () {
    let Resume = this.data.Resume
    await this.verification()
    this.removeDraft()
    resumeModel.resumePublish(Resume,
      res => {
        this.tip('发布成功！', 'publish')
    })
  },

  bindDateChange: function(e) {
    this.setData({
      'Resume.birthday': (e.detail.value).replace(/-/g, '/')
    })
  },

  async update () {
    await this.verification()
    let Resume = this.data.Resume
    if (Resume.phone.includes('*')) {
      delete Resume.phone
    }
    resumeModel.resumeUpdate(Resume, res => {
      this.tip('更新成功！')
    })
  },

  verification () {
    let Resume = this.data.Resume
    return new Promise((resolve, reject) => {
      if (!Resume.avatar) {
        wx.showToast({
          title: '请先添加头像',
          icon: 'none'
        })
        return reject(false)
      }
      if (!Resume.title) {
        wx.showToast({
          title: '请填写简历标题',
          icon: 'none'
        })
        return reject(false)
      }
      if (!Resume.name) {
        wx.showToast({
          title: '请填写姓名',
          icon: 'none'
        })
        return reject(false)
      }
      if (!Resume.sex) {
        wx.showToast({
          title: '请选择性别',
          icon: 'none'
        })
        return reject(false)
      }
      if (!Resume.birthday) {
        wx.showToast({
          title: '请选择生日',
          icon: 'none'
        })
        return reject(false)
      }
      if (!Resume.phone) {
        wx.showToast({
          title: '请填写联系电话',
          icon: 'none'
        })
        return reject(false)
      }
      if (Resume.phone.length != 11) {
        wx.showToast({
          title: '请填写正确的手机号',
          icon: 'none'
        })
        return reject(false)
      }
      if (!Resume.advantage) {
        wx.showToast({
          title: '请选择个人优势',
          icon: 'none'
        })
        return reject(false)
      }
      if (!Resume.jobState) {
        wx.showToast({
          title: '请选择是否在职',
          icon: 'none'
        })
        return reject(false)
      }
      if (!Resume.jobExperience) {
        wx.showToast({
          title: '请选择工作经验',
          icon: 'none'
        })
        return reject(false)
      }
      if (!Resume.chooseStation) {
        wx.showToast({
          title: '请选择求职岗位',
          icon: 'none'
        })
        return reject(false)
      }
      if (!Resume.expectedSalary) {
        wx.showToast({
          title: '请选择期望薪资',
          icon: 'none'
        })
        return reject(false)
      }
      if (!Resume.expectedCity) {
        wx.showToast({
          title: '请选择期望省市',
          icon: 'none'
        })
        return reject(false)
      }
      if (!Resume.selfIntroduction) {
        wx.showToast({
          title: '请填写自我介绍',
          icon: 'none'
        })
        return reject(false)
      }
      if (Resume.photoLifeList.length < 2) {
        wx.showToast({
          title: '请最少上传两张生活照',
          icon: 'none'
        })
        return reject(false)
      }
      if (Resume.photoWorkList.length < 2) {
        wx.showToast({
          title: '请最少上传两张工作照',
          icon: 'none'
        })
        return reject(false)
      }
      if (!Resume.verificationCode && this.data.showMsg) {
        wx.showToast({
          title: '请填写验证码',
          icon: 'none'
        })
        return reject(false)
      }
      resolve(true)
    })
  },

  confirmDialogTip() {
    wx.navigateBack({
      delta: 1
    })
  },

  onReady () {
    this.init()
  },

  inputChange (evevt) {
    let key = `Resume.${evevt.currentTarget.dataset.type}`
    if (key == 'Resume.phone') {
      // 手机号有改变时再显示发送验证码
      this.setData({
        showMsg: true
      })
    }
    this.setData({
      [key]: evevt.detail
    })
  },

  onDateChange(event) {
    this.setData({
      'Resume.birthday': event.detail.getValues().join('/')
    });
  },

  onDateInput(event) {
    this.setData({
      currentDate: event.detail
    });
  },

  uploadCover () {
    uploadImg.chooseImg(1,imgUrl => {
      this.setData({
        'Resume.avatar': imgUrl
      })
    })
  },

  onShowPopup (e) {
    // 打开弹窗
    wx.hideKeyboard()
    const which = e.currentTarget.dataset.key
    const key = `showPopup.${which}`
    this.setData({
      [key] : true
    })
  },

  onClosePopup () {
    console.log('--0000---')
    // 关闭弹窗
    for(let key in this.data.showPopup) {
      key = `showPopup.${key}`
      console.log(key)
      this.setData({
        [key]: false
      })
    }
  },

  onSex(e) {
    // 选择性别
    this.setData({
      'Resume.sex': e.detail
    })
  },

  onJobState(e) {
    // 选择是否在职
    this.setData({
      'Resume.jobState': e.detail
    })
  },

  onAdvantage(e) {
    // 选择个人优势
    this.setData({
      'Resume.advantage': e.detail
    })
  },

  onJobExperience(e) {
    // 选择工作经验
    this.setData({
      'Resume.jobExperience': e.detail.selected
    })
  },

  onChooseStation(e) {
    // 选择工作岗位
    this.setData({
      'Resume.chooseStation': e.detail
    })
  },

  onSalary(e) {
    // 选择期望薪资
    this.setData({
      'Resume.expectedSalary': e.detail.selected
    })
  },

  onExpectedCity(e) {
    // 选择期望城市
    this.setData({
      'Resume.expectedCity': e.detail
    })
  },

  getAdvantageList () {
    // 获取个人优势
    publishModel.getPublicTypes({
      tagKey: '技师标签',
      type: 0
    }, res => {
      this.setData({
        advantageList: res
      })
    })
  },

  getJobExperience () {
    // 获取工作经验
    publishModel.getPublicTypes({
      tagKey: '工作经验',
      type: 0
    }, res => {
      this.setData({
        jobExperienceList: res
      })
    })
  },

  getSalaryList () {
    // 获取期望薪资
    publishModel.getPublicTypes({
      tagKey: '薪资范围',
      type: 0
    }, res => {
      this.setData({
        salaryList: res
      })
    })
  },

  sendMsg () {
    if (this.data.Resume.phone.includes('*')) {
      wx.showToast({
        title: '请填写正确的手机号',
        icon: 'none'
      })
      this.setData({
        'Resume.phone': ''
      })
      return
    }
    let countDown = this.data.countDown
    const timer = setInterval(() => {
      countDown -= 1
      this.setData({
        countDown
      })
      if (countDown <= 0) {
        clearInterval(timer)
        this.setData({
          countDown: 60
        })
      }
    }, 1000)
    publishModel.sendMsg({
      PhoneNumbers: this.data.Resume.phone
    }, res => {
      wx.showToast({
        title: '发送成功',
        icon: 'none'
      })
    })
  },

  getResume () {
    // 获取发布过的简历
    resumeModel.resumeDetail(res => {
      if (!res) {
        // 没有简历的话查看是否有草稿
        this.setData({
          showRedPacketDialog: true
        })
        this.getDraft()
        return
      }
      this.setData({
        Resume: {photoLifeList: [], photoWorkList: [], ...res} || this.data.Resume,
        hasResume: !!res,
        showRedPacketDialog: !res
      })
      if(res.auditStatus == 2) {
        Dialog.alert({
          title: '审核未通过',
          message: `未通过原因：${res.remark} \n 请重新修改并提交审核。`,
        }).then(() => {
          // on close
        })
      }
      if(res.auditStatus == 3) {
        Dialog.alert({
          title: '简历已下架',
          message: `请重新修改并提交审核。`,
        }).then(() => {
          // on close
        })
      }
      if (res.auditStatus == 0) {
        Dialog.alert({
          message: '正在审核中，请耐心等待回复！',
        }).then(() => {
          // on close
        })
      }
    })
  },

  getJobsStationCategory () {
    // 获取岗位分类选项
    publishModel.getJobsStationCategory({}, res => {
      res = res.map
      console.log(res)
    })
  },


  touchmove(){
    // 空函数 防止滚动
  },

  removeImg (e) {
    const index = e.currentTarget.dataset.index
    let imgList = this.data.Resume.photoLifeList
    imgList.splice(index, 1)
    this.setData({
      'Resume.photoLifeList': imgList,
      'Resume.photoLife': imgList.join(',')
    })
  },

  removeWorkImg (e) {
    const index = e.currentTarget.dataset.index
    let imgList = this.data.Resume.photoWorkList
    imgList.splice(index, 1)
    this.setData({
      'Resume.photoWorkList': imgList,
      'Resume.photoWork': imgList.join(',')
    })
  },

  tip (title, type) {
    if (type == 'publish') {
      Dialog.alert({
        message: `恭喜你${this.data.totalMoney}元红包已到账 \n 信息审核通过后，红包即可提现！`,
        confirmButtonText: '邀请拿红包',
        cancelButtonText: '查看红包',
        showCancelButton: true,
        cancelButtonColor: '#23DEAF',
        confirmButtonOpenType: 'share'
      }).then(() => {
        wx.requestSubscribeMessage({
          tmplIds: ['-DHKrW9DRvbg3sEoVRYtcRxRyr-kYzyTN-9BNCY89rI', 'b7FIjt52cUMvTClpMJKJLe8lzi4rnQsWlUc7D5VYGoA', 'PbmE0p7hgtUXlZcUEgR_qBcP3tMhbe1-_wKNw7CkoZY'],
          complete (res) {
            wx.navigateBack()
          }
        })
      }).catch(() => {
        wx.requestSubscribeMessage({
          tmplIds: ['-DHKrW9DRvbg3sEoVRYtcRxRyr-kYzyTN-9BNCY89rI', 'b7FIjt52cUMvTClpMJKJLe8lzi4rnQsWlUc7D5VYGoA', 'PbmE0p7hgtUXlZcUEgR_qBcP3tMhbe1-_wKNw7CkoZY'],
          complete (res) {
            wx.redirectTo({
              url: `/packageA/pages/my-redpacket/my-redpacket`
            })
          }
        })
      })
    } else {
      Dialog.alert({
        title,
        message: '平台将在24小时内完成审核，请耐心等待！',
      }).then(() => {
        wx.requestSubscribeMessage({
          tmplIds: ['-DHKrW9DRvbg3sEoVRYtcRxRyr-kYzyTN-9BNCY89rI', 'b7FIjt52cUMvTClpMJKJLe8lzi4rnQsWlUc7D5VYGoA', 'PbmE0p7hgtUXlZcUEgR_qBcP3tMhbe1-_wKNw7CkoZY'],
          complete (res) {
            wx.navigateBack()
          }
        })
      })
    }
  },

  saveDraft() {
    wx.setStorageSync('resumeData', this.data.Resume)
    wx.showToast({
      title: '草稿保存成功！'
    })
  },

  getDraft() {
    const Resume = wx.getStorageSync('resumeData') || this.data.Resume
    this.setData({
      Resume
    })
  },

  removeDraft() {
    wx.removeStorageSync('resumeData')
  },

  closeDialog() {
    this.setData({
      showRedPacketDialog: false
    })
  },

  getPacketSize() {
    packetModel.getPacketSize(res => {
      res.forEach(item => {
        if (item.modeName == '求职') {
          this.setData({
            totalMoney: item.totalMoney
          })
        }
      })
    })
  },

  delete() {
    // 删除简历 测试用
    resumeModel.delete({
      id: this.data.Resume.id
    }, res => {
      wx.showToast({
        title: '删除成功',
        icon: 'none'
      })
      wx.navigateBack({
        delta: 1
      })
    })
  },

  init() {
    this.getAdvantageList()
    this.getJobExperience()
    this.getSalaryList()
    this.getResume()
    this.getPacketSize()
  }
})
